package com.echatim.service.app;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.commom.DBConst;
import com.echatim.broker.localbroadcast.SystemMessageLocalBroadcastEvent;
import com.echatim.entity.SystemMessage;
import com.echatim.entity.User;
import com.echatim.mapper.SystemMessageMapper;
import com.utils.Beans;
import com.utils.UIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author kong <androidsimu@163.com>
 * create by 2019/2/21 13:21
 * Description: echatim
 **/


@Slf4j
@DS("master")
@Service
public class SystemMessageService extends ServiceImpl<SystemMessageMapper, SystemMessage>  {
    public Long saveSystemMessage(User originUser, User targetUser, String category, String text){
        // 加入系统消息(群主)
        String body = Beans.json(new HashMap<String, Object>(){{
            put("body", text);
        }});
        SystemMessage systemMessage = new SystemMessage()
                .setUid(UIDUtils.gen())
                .setAppKey(targetUser.getAppKey())
                .setBody(body).setStatus(DBConst.EntryStatus.NORMAL.name())
                .setToTarget(targetUser.getAuid())
                .setType("TEXT")
                .setCategory(category)
                .setCreateTime(new Date());
        this.save(systemMessage);
        return systemMessage.getId();
    }

    // 设置消息为已读
    public void readSystemMessage(List<Long> msgIds){
        if(msgIds.isEmpty()){
            return;
        }
        List<SystemMessage> systemMessages = this.lambdaQuery().in(SystemMessage::getId, msgIds).list();
        systemMessages.forEach(v->v.setMessageRead(1));
        this.updateBatchById(systemMessages);
    }

    // 本地广播
    public void localBroadcast(SystemMessageLocalBroadcastEvent event){
        Object eventBus = SpringContextHolder.getApplicationContext().getBean("eventBus");
        if(eventBus == null){
            return;
        }
        Class clz = eventBus.getClass();
        try {
            Method post = clz.getDeclaredMethod("post", Object.class);
            post.invoke(eventBus, event);
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }

}
